<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>AI面试助手 - 开始面试</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background-color: #f8f9fa;
        }

        .navbar {
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .interview-container {
            max-width: 800px;
            margin: 40px auto;
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .interview-header {
            background-color: #165DFF;
            color: white;
            padding: 24px;
            text-align: center;
        }

        .interview-body {
            padding: 32px;
        }

        .question-card {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 24px;
            margin-bottom: 24px;
            border: 1px solid #e9ecef;
            transition: all 0.3s ease;
        }

        .question-card:hover {
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08);
        }

        .question-number {
            font-weight: bold;
            color: #165DFF;
            margin-bottom: 12px;
            display: block;
        }

        .question-text {
            font-size: 18px;
            color: #2c3e50;
            margin-bottom: 24px;
            line-height: 1.6;
        }

        .answer-input {
            width: 100%;
            min-height: 120px;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            resize: vertical;
            font-size: 16px;
        }

        .answer-input:focus {
            border-color: #165DFF;
            outline: none;
            box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.1);
        }

        .btn-group {
            margin-top: 24px;
            text-align: center;
        }

        .btn {
            padding: 10px 24px;
            border-radius: 6px;
            font-size: 16px;
            font-weight: 500;
            transition: all 0.3s ease;
            margin: 0 8px;
        }

        .btn-primary {
            background-color: #165DFF;
            border: none;
        }

        .btn-primary:hover {
            background-color: #0f4cd1;
            transform: translateY(-1px);
        }

        .btn-secondary {
            background-color: #6c757d;
            border: none;
        }

        .btn-secondary:hover {
            background-color: #5a6268;
        }

        .progress-container {
            margin-top: 24px;
            text-align: center;
        }

        .progress {
            height: 8px;
            border-radius: 4px;
            overflow: hidden;
            background-color: #e9ecef;
        }

        .progress-bar {
            background-color: #165DFF;
            height: 100%;
            transition: width 0.3s ease;
        }

        .progress-text {
            margin-top: 8px;
            color: #6c757d;
            font-size: 14px;
        }

        .resume-analysis {
            background-color: #e8f5e9;
            border-radius: 8px;
            padding: 20px;
            margin-top: 32px;
            border: 1px solid #c8e6c9;
        }

        .resume-analysis h4 {
            color: #2e7d32;
            margin-bottom: 16px;
        }

        .resume-analysis p {
            margin-bottom: 8px;
            color: #388e3c;
        }

        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .fade-out {
            animation: fadeOut 0.3s ease-out;
        }

        @keyframes fadeOut {
            from {
                opacity: 1;
                transform: translateY(0);
            }

            to {
                opacity: 0;
                transform: translateY(-10px);
            }
        }

        .notification {
            position: fixed;
            top: 80px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 6px;
            color: white;
            font-weight: 500;
            z-index: 1000;
            animation: slideIn 0.3s ease-out;
        }

        .notification-success {
            background-color: #4caf50;
        }

        .notification-error {
            background-color: #f44336;
        }

        @keyframes slideIn {
            from {
                transform: translateX(100%);
            }

            to {
                transform: translateX(0);
            }
        }

        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 2px solid rgba(255, 255, 255, .3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
    </style>
</head>

<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/">
                <i class="fas fa-robot me-2"></i>AI面试助手
            </a>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/new-interview/history">面试历史</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/logout">退出登录</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="interview-container">
        <div class="interview-header">
            <h2>AI面试进行中</h2>
            <p>请回答以下问题，展示您的专业知识和能力</p>
        </div>

        <div class="interview-body">
            <input type="hidden" id="interviewId" th:value="${interviewId}">
            <input type="hidden" id="totalQuestions" value="5">
            <input type="hidden" id="jobTitle" th:value="${jobTitle}">

            <div id="question-container" class="question-card fade-in">
                <span id="questionNumber" class="question-number">问题 1 / <span
                        th:text="${questions.size()}">5</span></span>
                <p id="questionText" class="question-text" th:text="${questions[0]}">加载中...</p>
                <textarea id="answerInput" class="answer-input" placeholder="请输入您的回答..."></textarea>
            </div>

            <div class="btn-group">
                <button id="saveDraftBtn" class="btn btn-secondary">
                    <i class="fas fa-save me-2"></i>保存草稿
                </button>
                <button id="nextQuestionBtn" class="btn btn-primary">
                    下一个问题<i class="fas fa-arrow-right ml-2"></i>
                </button>
            </div>

            <div class="progress-container">
                <div class="progress">
                    <div id="progressBar" class="progress-bar" role="progressbar" style="width: 20%" aria-valuenow="20"
                        aria-valuemin="0" aria-valuemax="100"></div>
                </div>
                <div id="progressText" class="progress-text">已完成 1/<span th:text="${questions.size()}">5</span> 问题</div>
            </div>

            <div class="resume-analysis">
                <h4><i class="fas fa-chart-line me-2"></i>简历分析建议</h4>
                <p th:text="${resumeAnalysis.summary}">加载中...</p>
                <p><strong>优势：</strong><span th:text="${resumeAnalysis.strengths}">加载中...</span></p>
                <p><strong>改进空间：</strong><span th:text="${resumeAnalysis.areasForImprovement}">加载中...</span></p>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // 获取DOM元素
            const interviewId = document.getElementById('interviewId').value;
            const totalQuestionsInput = document.getElementById('totalQuestions');
            const questionContainer = document.getElementById('question-container');
            const questionNumber = document.getElementById('questionNumber');
            const questionText = document.getElementById('questionText');
            const answerInput = document.getElementById('answerInput');
            const nextQuestionBtn = document.getElementById('nextQuestionBtn');
            const saveDraftBtn = document.getElementById('saveDraftBtn');
            const progressBar = document.getElementById('progressBar');
            const progressText = document.getElementById('progressText');

            // 初始化变量
            let currentQuestionIndex = 0;
            let totalQuestions = 5; // 固定为5道题
            let answers = {};
            let questions = [];
            const jobTitle = document.getElementById('jobTitle').value;

            console.log('初始化面试参数:', {
                interviewId: interviewId,
                currentQuestionIndex: currentQuestionIndex,
                totalQuestions: totalQuestions
            });

            // 初始化面试
            function initInterview() {
                // 确保重置为0，防止本地存储或其他原因导致索引异常
                currentQuestionIndex = 0;
                console.log('强制重置currentQuestionIndex为0');

                // 从页面获取初始问题
                const initialQuestion = questionText.textContent.trim();
                if (initialQuestion && initialQuestion !== '加载中...') {
                    questions = [initialQuestion]; // 重置问题列表，确保只有初始问题
                    console.log('添加初始问题:', initialQuestion);
                }

                // 检查本地存储是否有保存的答案
                const savedAnswers = localStorage.getItem(`interview_${interviewId}_answers`);
                if (savedAnswers) {
                    try {
                        answers = JSON.parse(savedAnswers);
                        if (answers[currentQuestionIndex]) {
                            answerInput.value = answers[currentQuestionIndex];
                        }
                        console.log('加载保存的答案:', answers);
                    } catch (e) {
                        console.error('解析保存的答案失败：', e);
                    }
                }

                // 更新UI
                updateQuestionUI();

                // 显示面试开始提示
                setTimeout(() => {
                    showNotification(`面试开始！本次面试共${totalQuestions}道题，将结合您的简历和${jobTitle}岗位要求进行提问。`, 'success');
                }, 500);
            }

            // 显示通知
            function showNotification(message, type = 'success') {
                console.log('显示通知:', message, type);
                const notification = document.createElement('div');
                notification.className = `notification notification-${type}`;
                notification.textContent = message;
                document.body.appendChild(notification);

                setTimeout(() => {
                    notification.remove();
                }, 3000);
            }

            // 保存答案
            function saveAnswer() {
                return new Promise((resolve, reject) => {
                    const answer = answerInput.value.trim();

                    if (!answer) {
                        console.log('答案为空，跳过保存');
                        resolve(); // 空答案也继续，不阻止流程
                        return;
                    }

                    answers[currentQuestionIndex] = answer;
                    console.log('保存答案:', currentQuestionIndex, answer);

                    // 保存到本地存储
                    localStorage.setItem(`interview_${interviewId}_answers`, JSON.stringify(answers));

                    // 保存到服务器
                    fetch(`/new-interview/save-answer?interviewId=${interviewId}&questionIndex=${currentQuestionIndex}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'text/plain'
                        },
                        body: answer
                    })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('保存失败');
                            }
                            return response.text();
                        })
                        .then(data => {
                            console.log('答案保存成功');
                            showNotification('答案保存成功');
                            resolve();
                        })
                        .catch(error => {
                            console.error('保存答案失败：', error);
                            showNotification('保存失败，请稍后重试', 'error');
                            reject(error);
                        });
                });
            }

            // 生成下一个问题
            function generateNextQuestion() {
                console.log('生成下一个问题，当前索引:', currentQuestionIndex);

                // 安全检查：如果索引异常大，强制重置到安全值
                if (currentQuestionIndex > 10) {
                    console.error('检测到异常索引值，强制重置为0:', currentQuestionIndex);
                    currentQuestionIndex = 0;
                    showNotification('系统检测到异常状态，已重置面试进度', 'warning');
                    updateQuestionUI();
                    return;
                }

                // 检查是否已达到后端限制的5个问题
                if (currentQuestionIndex >= 4) {
                    console.log('已达到最大问题数量限制，不调用API');
                    showNotification('已完成所有问题，即将提交面试', 'success');

                    // 恢复按钮状态
                    nextQuestionBtn.disabled = false;
                    nextQuestionBtn.innerHTML = '<i class="fas fa-check me-2"></i>提交所有答案';
                    nextQuestionBtn.onclick = submitInterview;

                    // 更新UI以反映已达到最大问题数量
                    updateQuestionUI();
                    return;
                }

                console.log('准备调用API生成下一个问题，当前索引:', currentQuestionIndex);

                // 显示加载状态
                nextQuestionBtn.disabled = true;
                nextQuestionBtn.innerHTML = '<span class="loading-spinner"></span> 生成问题中...';

                // 调用API生成下一个问题，使用正确的路径和参数格式
                fetch(`/new-interview/generate-next-question?interviewId=${interviewId}&currentQuestionIndex=${currentQuestionIndex}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({})
                })
                    .then(response => {
                        if (!response.ok) {
                            // 获取后端返回的具体错误信息
                            return response.text().then(errorMessage => {
                                throw new Error('生成问题失败: ' + errorMessage);
                            });
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log('收到新问题:', data);

                        // 安全地更新问题索引，确保不超过后端限制的5个问题（索引4）
                        // 如果后端返回的索引异常，就使用当前索引+1
                        let newIndex = currentQuestionIndex + 1;
                        if (data.questionIndex !== undefined && data.questionIndex >= 0 && data.questionIndex <= 4) {
                            newIndex = data.questionIndex;
                        } else if (data.questionIndex) {
                            console.warn('后端返回的问题索引异常:', data.questionIndex, '使用当前索引+1替代');
                        }
                        currentQuestionIndex = Math.min(newIndex, 4);
                        console.log('更新后的问题索引:', currentQuestionIndex);

                        // 更新问题总数
                        if (data.totalQuestions) {
                            totalQuestions = Math.min(data.totalQuestions, 5);
                        } else {
                            totalQuestions = 5; // 默认为后端限制的最大问题数
                        }
                        console.log('更新后的问题总数:', totalQuestions);

                        // 添加新问题到列表，确保问题列表不会重复添加
                        if (!questions.includes(data.question)) {
                            questions.push(data.question);
                            console.log('问题列表更新:', questions);
                        } else {
                            console.log('问题已存在，不重复添加');
                        }

                        // 更新UI
                        updateQuestionUI();

                        // 恢复按钮状态
                        nextQuestionBtn.disabled = false;
                        // 检查是否是最后一个问题
                        if (currentQuestionIndex >= totalQuestions - 1) {
                            nextQuestionBtn.innerHTML = '<i class="fas fa-check me-2"></i>提交所有答案';
                        } else {
                            nextQuestionBtn.innerHTML = '下一个问题<i class="fas fa-arrow-right ml-2"></i>';
                        }
                    })
                    .catch(error => {
                        console.error('生成问题失败：', error);
                        showNotification(error.message || '生成问题失败，请稍后重试', 'error');

                        // 恢复按钮状态
                        nextQuestionBtn.disabled = false;
                        nextQuestionBtn.innerHTML = '下一个问题<i class="fas fa-arrow-right ml-2"></i>';
                    });
            }

            // 处理下一个问题
            function handleNextQuestion() {
                console.log('处理下一个问题，当前索引:', currentQuestionIndex);

                // 安全检查：如果索引异常大，强制重置到安全值
                if (currentQuestionIndex > 10) {
                    console.error('检测到异常索引值，强制重置为0:', currentQuestionIndex);
                    currentQuestionIndex = 0;
                    showNotification('系统检测到异常状态，已重置面试进度', 'warning');
                    updateQuestionUI();
                    nextQuestionBtn.disabled = false;
                    nextQuestionBtn.innerHTML = '下一个问题<i class="fas fa-arrow-right ml-2"></i>';
                    return;
                }

                // 获取当前答案
                const currentAnswer = answerInput.value.trim();

                // 检查是否已回答问题（除了最后一个问题外都需要回答）
                if (currentQuestionIndex < totalQuestions - 1 && !currentAnswer) {
                    showNotification('请先回答当前问题', 'error');
                    return;
                }

                // 显示加载状态
                nextQuestionBtn.disabled = true;
                nextQuestionBtn.innerHTML = '<span class="loading-spinner"></span> 处理中...';

                // 先保存当前答案
                saveAnswer()
                    .then(() => {
                        // 检查是否已达到后端限制的5个问题（优先级最高）
                        if (currentQuestionIndex >= 4) {
                            console.log('已达到最大问题数量限制，提交面试');
                            showNotification('已完成所有问题，即将提交面试', 'success');
                            submitInterview();
                            return;
                        }

                        // 检查是否是最后一个问题
                        if (currentQuestionIndex >= totalQuestions - 1) {
                            console.log('已完成所有问题，提交面试');
                            showNotification('已完成所有问题，即将提交面试', 'success');
                            submitInterview();
                            return;
                        }

                        // 问题卡片淡出动画
                        questionContainer.classList.add('fade-out');
                        setTimeout(() => {
                            console.log('准备生成下一个问题，当前索引:', currentQuestionIndex, '总问题数:', totalQuestions);
                            // 安全地递增索引，然后再调用generateNextQuestion
                            if (currentQuestionIndex < 4) { // 确保不超过后端限制
                                currentQuestionIndex++;
                                console.log('索引递增后的值:', currentQuestionIndex);
                            } else {
                                console.log('索引已达到或超过限制，不递增');
                            }
                            // 生成下一个问题
                            generateNextQuestion();
                            // 问题卡片淡入动画
                            questionContainer.classList.remove('fade-out');
                            questionContainer.classList.add('fade-in');
                        }, 300);
                    })
                    .catch(error => {
                        console.error('保存答案失败：', error);
                        // 恢复按钮状态
                        nextQuestionBtn.disabled = false;
                        nextQuestionBtn.innerHTML = '下一个问题<i class="fas fa-arrow-right ml-2"></i>';
                        showNotification('保存失败，请稍后重试', 'error');
                    });
            }

            // 更新问题UI
            function updateQuestionUI() {
                console.log('更新UI，当前索引:', currentQuestionIndex, '总问题数:', totalQuestions);

                // 安全检查，确保索引有效
                if (currentQuestionIndex < 0) {
                    currentQuestionIndex = 0;
                    console.log('修正负索引:', currentQuestionIndex);
                }

                if (currentQuestionIndex < questions.length) {
                    questionNumber.textContent = `问题 ${currentQuestionIndex + 1} / ${totalQuestions}`;
                    questionText.textContent = questions[currentQuestionIndex];
                    answerInput.value = answers[currentQuestionIndex] || '';

                    // 更新进度条
                    const progressPercentage = Math.round(((currentQuestionIndex + 1) / totalQuestions) * 100);
                    progressBar.style.width = `${progressPercentage}%`;
                    progressBar.setAttribute('aria-valuenow', progressPercentage);
                    progressText.textContent = `已完成 ${currentQuestionIndex + 1}/${totalQuestions} 问题`;

                    // 更新按钮文本 - 优化条件判断，确保只有真正完成5个问题时才显示提交按钮
                    if (currentQuestionIndex >= 4) {
                        console.log('已达到最大问题数量限制，显示提交按钮');
                        nextQuestionBtn.innerHTML = '<i class="fas fa-check me-2"></i>提交所有答案';
                        nextQuestionBtn.onclick = submitInterview;
                    } else {
                        nextQuestionBtn.innerHTML = '下一个问题<i class="fas fa-arrow-right ml-2"></i>';
                        nextQuestionBtn.onclick = handleNextQuestion;
                    }
                }
            }

            // 提交面试
            function submitInterview() {
                console.log('提交面试');

                // 显示加载状态
                nextQuestionBtn.disabled = true;
                nextQuestionBtn.innerHTML = '<span class="loading-spinner"></span> 提交中...';

                // 保存最后一个答案
                saveAnswer()
                    .then(() => {
                        // 创建表单并提交
                        const form = document.createElement('form');
                        form.method = 'POST';
                        form.action = `/new-interview/submit-answers?interviewId=${interviewId}`;

                        // 添加所有答案
                        for (let i = 0; i < questions.length; i++) {
                            const input = document.createElement('input');
                            input.type = 'hidden';
                            input.name = `answer_${i}`;
                            input.value = answers[i] || '';
                            form.appendChild(input);
                        }

                        document.body.appendChild(form);
                        form.submit();
                    })
                    .catch(error => {
                        console.error('提交失败：', error);
                        showNotification('提交失败，请稍后重试', 'error');
                        nextQuestionBtn.disabled = false;
                        nextQuestionBtn.innerHTML = '<i class="fas fa-check me-2"></i>提交所有答案';
                    });
            }

            // 初始化面试
            initInterview();

            // 绑定事件监听器
            saveDraftBtn.addEventListener('click', () => {
                saveAnswer().catch(error => {
                    console.error('保存草稿失败：', error);
                });
            });

            nextQuestionBtn.addEventListener('click', handleNextQuestion);

            // 键盘快捷键：Ctrl+Enter 保存答案
            answerInput.addEventListener('keydown', function (event) {
                if (event.ctrlKey && event.key === 'Enter') {
                    event.preventDefault();
                    saveAnswer().catch(error => {
                        console.error('保存答案失败：', error);
                    });
                }
            });

            // 页面卸载时自动保存
            window.addEventListener('beforeunload', () => {
                const answer = answerInput.value.trim();
                if (answer) {
                    answers[currentQuestionIndex] = answer;
                    localStorage.setItem(`interview_${interviewId}_answers`, JSON.stringify(answers));
                }
            });

            console.log('面试界面初始化完成');
        });
    </script>
</body>

</html>